package com.bujunjie.study.realtime.common.util;

import com.bujunjie.study.realtime.common.constant.FlinkConstant;
import com.google.common.base.CaseFormat;
import org.apache.commons.beanutils.BeanUtils;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>Mysql 的jdbc 工具类</p>
 *
 * @author bu.junjie
 * @version 1.0.0
 * @createTime 2025/9/13 10:05
 */
public class JdbcUtil {

    /**
     * <p>获取 mysql 的连接</p>
     *
     * @param
     * @return 返回 mysql 的连接
     * @author bu.junjie
     * @date 2025/9/13 10:13
     */
    public static Connection getMySQLConnection() throws Exception {
        //注册驱动
        Class.forName(FlinkConstant.MYSQL_DRIVER);
        //建立连接
        java.sql.Connection conn = DriverManager.getConnection(FlinkConstant.MYSQL_URL, FlinkConstant.MYSQL_USER_NAME, FlinkConstant.MYSQL_PASSWORD);
        return conn;
    }

    /**
     * <p>关闭连接</p>
     *
     * @param conn mysql 的连接
     * @return
     * @author bu.junjie
     * @date 2025/9/13 10:14
     */
    public static void closeMySQLConnection(Connection conn) throws SQLException {
        if (conn != null && !conn.isClosed()) {
            conn.close();
        }
    }


    /**
     * <p> 查询 mysql 的数据</p>
     *
     * @param conn               连接
     * @param sql                查询的 sql 语句
     * @param clz                封装的泛型
     * @param isUnderlineToCamel 驼峰
     * @return 返回查询的对象
     * @author bu.junjie
     * @date 2025/9/13 10:15
     */
    public static <T> List<T> queryList(Connection conn, String sql, Class<T> clz, boolean... isUnderlineToCamel) throws Exception {
        List<T> resList = new ArrayList<>();
        // 默认不执行下划线转驼峰
        boolean defaultIsUToC = false;

        if (isUnderlineToCamel.length > 0) {
            defaultIsUToC = isUnderlineToCamel[0];
        }
        PreparedStatement ps = conn.prepareStatement(sql);
        ResultSet rs = ps.executeQuery();
        ResultSetMetaData metaData = rs.getMetaData();
        while (rs.next()) {
            //通过反射创建一个对象，用于接收查询结果
            T obj = clz.newInstance();
            for (int i = 1; i <= metaData.getColumnCount(); i++) {
                String columnName = metaData.getColumnName(i);
                Object columnValue = rs.getObject(i);
                //给对象的属性赋值
                if (defaultIsUToC) {
                    columnName = CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, columnName);
                }
                BeanUtils.setProperty(obj, columnName, columnValue);
            }
            resList.add(obj);
        }

        return resList;
    }
}
